﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using XMK.Utils;
using System.Text;

namespace XMK.Tadong.ServiceWeb.Handlers
{
    /// <summary>
    /// download 的摘要说明
    /// </summary>
    public class download : IHttpHandler
    {
        public string ContentType { get; set; }//文件类型（HTTP MIME）
        public bool IsInline { get; set; }//是否在线打开
        public string Attach { get; set; }//文件下载后显示名称
        public string AttachUrl { get; set; }//文件下载地址
        public string AttachName { get; set; }
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request["attach"] == null || context.Request["type"] == null)
                return;
            this.Attach = context.Request["attach"];
            this.AttachName = context.Request["attachname"];
            this.AttachUrl = context.Server.MapPath("~/attach") + "\\" + context.Request["type"] + "\\" + Attach.Replace("/", "\\");
            string fileExtension = this.Attach.Substring(this.Attach.LastIndexOf(".") + 1).ToLower();
            switch (fileExtension)
            {
                case "html":
                case "htm":
                    this.IsInline = true;
                    this.ContentType = "text/html";
                    break;
                default:
                    this.IsInline = false;
                    this.ContentType = "application/octet-stream";
                    break;
            }
            SetResponse();
        }
        /// <summary>
        /// 对附件返回进行填充
        /// </summary>
        public void SetResponse()
        {
            try
            {
                LogHelper.WriteLog("Download", LogType.Info, "[文件下载开始:" + DateTime.Now.ToString() + "][文件:" + this.AttachUrl + "]");
                SetResponse(this.ContentType, this.IsInline, string.IsNullOrEmpty(this.AttachName) ? this.Attach.Substring(this.Attach.LastIndexOf("/") + 1) : this.AttachName, this.AttachUrl);
                LogHelper.WriteLog("Download", LogType.Info, "[文件下载结束:" + DateTime.Now.ToString() + "][文件:" + this.AttachUrl + "]");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("Download", LogType.Info, "[文件下载异常:" + DateTime.Now.ToString() + "][文件:" + this.AttachUrl + "][异常信息：" + ex.Message + "]");
                HttpContext.Current.Response.Write("文件下载出错，请联系管理员");
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Close();
            }
        }

        /// <summary>
        /// 对附件返回进行填充
        /// </summary>
        /// <param name="contentType">application/octet-stream、application/pdf、text/plain</param>
        /// <param name="isInline">是否在线打开(android系统pdf时需要否)</param>
        /// <param name="attachName">文件下载后显示名称</param>
        /// <param name="attachUrl">附件绝对url</param>
        protected void SetResponse(string contentType, bool isInline, string attachName, string attachUrl)
        {
            FileStream stream = new FileStream(attachUrl, FileMode.Open);
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Close();
            HttpContext.Current.Response.Charset = "gb2312";
            HttpContext.Current.Response.ContentEncoding = Encoding.Default;
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
            string contentDisposition = isInline ? "inline" : "attachment";
            HttpContext.Current.Response.AddHeader("Content-Disposition", contentDisposition + ";filename=" + HttpUtility.UrlEncode(attachName, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentType = contentType;
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Close();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}